πΎ Bit Manipulation
Bit tricks turn scans into single CPU instructions. The arsenal is small but the payoff is huge β memorize the idioms below and they will appear everywhere.
This category contains 17 problems. Use the patterns below to recognize what's being asked, then jump to the problem list at the bottom.
π§ Key Patternsβ
- XOR for "find unique" β
a ^ a = 0,a ^ 0 = a. Single Number family. - Clear lowest set bit β
n & (n - 1)β count set bits, power-of-two check. - Bitmask DP β State = subset of items, often up to ~20 elements.
- Bit-by-bit reconstruction β Sum each bit position mod 3, mod k, etc.
- Built-ins β
BitOperations.PopCount,LeadingZeroCount,TrailingZeroCount(C#).
β οΈ Common Pitfallsβ
- Signed vs unsigned shifts.
>>on negativeintkeeps the sign bit. Use(uint). - Operator precedence:
(x & 1) == 0needs the parens.
π Study Resourcesβ
πΊ Videosβ
π Booksβ
- Hacker's Delight β Henry S. Warren β The definitive bit-twiddling reference
- Competitive Programming Handbook β Laaksonen β Ch. 10
π Articles & Referencesβ
π» All Bit Manipulation Problemsβ
Add Binary
LeetCode 67 | Difficulty: Easy
Biggest Single Number
LeetCode 619 | Difficulty: Easy
Bitwise AND of Numbers Range
LeetCode 201 | Difficulty: Medium
Counting Bits
LeetCode 338 | Difficulty: Easy
Gray Code
LeetCode 89 | Difficulty: Medium
Hamming Distance
LeetCode 461 | Difficulty: Easy
Missing Number
LeetCode 268 | Difficulty: Easy
Number of 1 Bits
LeetCode 191 | Difficulty: Easy
Power of Four
LeetCode 342 | Difficulty: Easy
Power of Three
LeetCode 326 | Difficulty: Easy
Power of Two
LeetCode 231 | Difficulty: Easy
Prime Number of Set Bits in Binary Representation
LeetCode 767 | Difficulty: Easy
Reverse Bits
LeetCode 190 | Difficulty: Easy
Single Number
LeetCode 136 | Difficulty: Easy
Single Number II
LeetCode 137 | Difficulty: Medium
Sort Integers by The Number of 1 Bits
LeetCode 1458 | Difficulty: Easy
Total Hamming Distance
LeetCode 477 | Difficulty: Medium